# -*- coding:utf8 -*-
import json
import traceback
import pyssdb
from scrapy import Request, FormRequest
from squirrel_core.commons.utils.get_config import get_config
from squirrel_core.frame.spider_makaka import MakakaSpider


class itra_login(MakakaSpider):
    name = "itra_login"
    start_url = "https://itra.run/"
    login_url = "https://itra.run/Account/Login"
    header = {
        "Host": "itra.run",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:138.0) Gecko/20100101 Firefox/138.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br, zstd",
    }

    race_header = {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "accept-encoding": "gzip, deflate, br",
        "accept-language": "zh,zh-CN;q=0.9",
        "cache-control": "max-age=0",
        "content-type": "application/x-www-form-urlencoded",
        "upgrade-insecure-requests": "1",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
        "Host": "itra.run"
    }

    specific_settings = {
        'COOKIES_ENABLED': True,
        'HTTPERROR_ALLOWED_CODES': [302]
    }
    handle_httpstatus_list = [302]

    base_config = get_config(sections="base")
    ssdb_host = base_config.get('ssdb_host')
    ssdb_port = base_config.get('ssdb_port')

    need_ssdbstore_dup = True
    serialNumber = ""

    def get_ext_requests_or_urls(self, data=None):
        if data and isinstance(data, str):
            data = json.loads(data)
        self.serialNumber = data.get("serialNumber", "")

        email = data.get("spider_config", {}).get("email", "")
        pwd = data.get("spider_config", {}).get("password", "")
        if not all([pwd, email]):
            self.logger.info("参数不全，请仔细核对")
            self.upload_procedure({"serialNumber": self.serialNumber, "code": 101, "message": "参数不全，请仔细核对"})
            self.close_after_idle = True
            self.force_to_close_spider = True
        else:
            self.upload_procedure({"serialNumber": self.serialNumber, "code": 100, "message": "任务启动成功"})
            yield Request(url=self.start_url, callback=self.parse, dont_filter=True, errback=self.err_parse,
                          headers=self.header, meta={"email": email, "pwd": pwd})

    def parse(self, response, **kwargs):
        try:
            self.logger.info("开始登陆")
            email = response.meta.get("email", "")
            pwd = response.meta.get("pwd", "")
            cookie = "; ".join([i.decode().split(";")[0] for i in response.headers.getlist("Set-Cookie")])
            self.race_header["Cookie"] = cookie
            token = response.xpath("//input[@name='__RequestVerificationToken']/@value").extract_first()
            login_data = {"Input.Email": email, "Input.Password": pwd, "__RequestVerificationToken": token}
            yield FormRequest(url=self.login_url, headers=self.race_header, formdata=login_data,
                              meta={"token": token},
                              errback=self.err_parse, callback=self.parse_login, dont_filter=True)
        except Exception:
            self.logger.info(f"登陆时出错：{traceback.format_exc()}")

    def parse_login(self, response):
        try:
            self.logger.info("开始保存cookie")
            cookie = "; ".join([i.decode().split(";")[0] for i in response.headers.getlist("Set-Cookie")])
            c = pyssdb.Client(host=self.ssdb_host, port=self.ssdb_port)
            c.qclear("itra_cookie")
            c.qpush_front("itra_cookie", cookie)
            c.disconnect()
        except Exception:
            self.logger.info(f"保存cookie时出错：{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")
